package com.example.spirngbootdemo.config;

/**
 * Description:
 *
 * @author Yang
 * create time 2021-10-21 23:19
 * @since 0.0.1
 */

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Aspect
@Component
@Order(-10000)
public abstract class MdcInterceptor {
    protected final static String LOG_ID = "requestId";

    @Pointcut("execution(* com.example.spirngbootdemo..*.*(..)) || @annotation(com.example.spirngbootdemo.annotation.LogTrack)")
    public void pointCut() {

    }

    @Around(value = "pointCut()")
    public Object invoke(ProceedingJoinPoint point) throws Throwable {
        Object result;
        try {
            setTradeId();
            result = point.proceed(point.getArgs());
            removeTraceId();
        } catch (Throwable throwable) {
            throw throwable;
        } finally {
            removeTraceId();
        }
        return result;
    }

    /**
     * 设置traceId
     */
    public static void setTradeId() {
        try {
            MDC.put(LOG_ID,UUID.randomUUID().toString());
        } catch (Exception e) {
            log.error("set log no exception", e);
        }
    }

    /**
     * remove traceId
     */
    public static void removeTraceId() {
        try {
            MDC.remove(LOG_ID);
        } catch (Exception e) {
            log.error("remove log no exception", e);
        }
    }
}